package com.mazaiting.redeye.module.me

import android.content.Context
import android.content.Intent
import android.provider.MediaStore
import android.text.TextUtils
import android.widget.Toast
import cn.smssdk.EventHandler
import cn.smssdk.SMSSDK
import com.mazaiting.easy.app.IApplicationComponent
import com.mazaiting.easy.base.activity.BaseLoadingActivity
import com.mazaiting.log.L
import com.mazaiting.redeye.R
import com.mazaiting.redeye.base.ApplicationComponentImpl
import com.mazaiting.redeye.bean.ImageBean
import com.mazaiting.redeye.bean.UserBean
import com.mazaiting.redeye.bean.VerifyCodeBean
import com.mazaiting.redeye.utils.ActivityUtil
import kotlinx.android.synthetic.main.activity_avatar.*

/**
 * 头像 Activity
 */
class AvatarActivity : BaseLoadingActivity<AvatarPresenter>(), AvatarContract.View {

    companion object {
        /**
         * 头像地址
         */
        private const val URL_AVATAR = "url_avatar"
        /**
         * 相册请求码
         */
        private const val CODE_ALBUM = 0x1000

        /**
         * 开启头像页面
         * @param context 上下文
         * @param url 头像地址
         */
        fun newInstance(context: Context, url:String) {
            val intent = Intent(context, AvatarActivity::class.java)
            // 设置头像
            intent.putExtra(URL_AVATAR, url)
            context.startActivity(intent)
        }
    }

    /**
     * 手机号
     */
    private var mPhoneNumber: String = ""

    private val eventHandler = object : EventHandler() {
        override fun afterEvent(event: Int, result: Int, data: Any?) {
            super.afterEvent(event, result, data)
            runOnUiThread {
                L.d("event: $event, result: $result, data: $data")
                if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    if (result == SMSSDK.RESULT_COMPLETE) {
                        // 请注意，此时只是完成了发送验证码的请求，验证码短信还需要几秒钟之后才送达
                        Toast.makeText(this@AvatarActivity, "发送成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@AvatarActivity, (data as Throwable).message, Toast.LENGTH_SHORT).show()
                    }
                } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    if (result == SMSSDK.RESULT_COMPLETE) {
                        Toast.makeText(this@AvatarActivity, "验证成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(this@AvatarActivity, (data as Throwable).message, Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }
    }

    /**
     * 验证验证码
     * @param phoneNumber 手机号
     * @param verifyCode 验证码
     */
    private fun submitSms(phoneNumber: String, verifyCode: String) {
//        SMSSDK.submitVerificationCode("86", phoneNumber, verifyCode)
        val userBean = UserBean()
        // 手机号
        userBean.phone = phoneNumber
        presenter?.updatePhone(VerifyCodeBean(verifyCode, userBean))
    }

    /**
     * 发送验证码
     * @param phoneNumber 手机号
     */
    private fun sendSms(phoneNumber: String) {
        // 在尝试读取通信录时以弹窗提示用户（可选功能）
        SMSSDK.setAskPermisionOnReadContact(true)

        // 注册一个事件回调，用于处理SMSSDK接口请求的结果
        SMSSDK.registerEventHandler(eventHandler)

        // 请求验证码，其中country表示国家代码，如“86”；phone表示手机号码，如“13800138000”
        SMSSDK.getVerificationCode("86", phoneNumber)

        // 提交验证码，其中的code表示验证码，如“1357”
//        SMSSDK.submitVerificationCode(country, phone, code);
    }

    override fun onDestroy() {
        // 使用完EventHandler需注销，否则可能出现内存泄漏
        SMSSDK.unregisterEventHandler(eventHandler)
        super.onDestroy()
    }

    override fun getContentLayout(): Int = R.layout.activity_avatar

    override fun inject(applicationComponent: IApplicationComponent?) {
        DaggerAvatarComponent
            .builder()
            .applicationComponentImpl(applicationComponent as ApplicationComponentImpl)
            .build()
            .inject(this)
    }

    override fun initData() {
        // 上传图片按钮点击监听
        avatar_mb_upload.setOnClickListener {
            ActivityUtil.startAlbumActivity(this, CODE_ALBUM)
        }
        // 发送验证码按钮
        avatar_mb_verify_code.setOnClickListener {
            // 获取手机号
            mPhoneNumber = avatar_tiet_phone_number.text.toString().trim()
            // 检测手机号是否为空
            if (TextUtils.isEmpty(mPhoneNumber)) {
                Toast.makeText(this@AvatarActivity, "手机号不能为空", Toast.LENGTH_SHORT).show()
            } else {
                sendSms(mPhoneNumber)
            }
        }
        // 绑定手机号
        avatar_mb_bind_phone_number.setOnClickListener {
            // 获取手机号
            val verifyCode = avatar_tiet_verify_code.text.toString().trim()
            // 检测手机号是否为空
            if (TextUtils.isEmpty(mPhoneNumber)) {
                Toast.makeText(this@AvatarActivity, "手机号不能为空", Toast.LENGTH_SHORT).show()
            } else {
                // 检测验证码是否为空
                if (TextUtils.isEmpty(verifyCode)) {
                    Toast.makeText(this@AvatarActivity, "验证码不能为空", Toast.LENGTH_SHORT).show()
                } else {
                    submitSms(mPhoneNumber, verifyCode)
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        // 判断请求码是否为相册码
        if (CODE_ALBUM == requestCode) {
            if (null != data) {
                // 获取选择图片 URI
                val selectedImageUri = data.data
                // 相册媒体数据列
                val filePathColumns = arrayOf(MediaStore.Images.Media.DATA)
                if (null != selectedImageUri) {
                    // 查询数据
                    val cursor = contentResolver.query(selectedImageUri, filePathColumns, null, null, null)
                    // 判断是否为空
                    if (null != cursor) {
                        // 移动到第一个位置
                        cursor.moveToFirst()
                        // 获取列
                        val index = cursor.getColumnIndex(filePathColumns[0])
                        // 获取图片路径
                        val imagePath = cursor.getString(index)
                        // 关闭游标
                        cursor.close()
                        // 更新头像
                        presenter?.updateAvatar(imagePath)
                        // 上传图片
                        presenter?.uploadImage(imagePath)
                    }
                }
            }
        }
    }

    override fun uploadSuccess(imageBean: ImageBean) {
        L.d("上传成功: " + imageBean.url)
        Toast.makeText(this@AvatarActivity, "上传成功", Toast.LENGTH_SHORT).show()
    }

    override fun uploadError(msg: String) {
        Toast.makeText(this@AvatarActivity, msg, Toast.LENGTH_SHORT).show()
    }

    override fun updateAvatarSuccess() {
        Toast.makeText(this@AvatarActivity, "头像更新成功", Toast.LENGTH_SHORT).show()
    }

    override fun updateAvatarError(msg: String) {
        Toast.makeText(this@AvatarActivity, "头像更新成功", Toast.LENGTH_SHORT).show()
    }

}
